package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.Border;
import javax.swing.filechooser.FileNameExtensionFilter;

import main.Conference;
import main.Manuscript;
import main.User;


//TODO Deadlines for Author check
/**
 * AuthorSubmitsFrame
 * 
 * Cristopher added Serializable
 * 
 * @author Daniel Anderson - Back End
 * @author Amandeep - GUI
 * @version 12/3
 */
public class AuthorSubmitsFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	private final JFileChooser my_file_chooser = new JFileChooser();
	
	//GUI Stuff
	private JFrame my_mainGUI;
	private JPanel my_title_panel;
	private JPanel my_submit_panel;
	private JPanel my_upload_panel;
	private JLabel my_current_selected;
	private JTextField my_text_field;
	
	//Data Stuff
	private User my_user;
	private Conference my_conference;
	private File my_selected_file;
	//private Manuscript my_selected_manuscript;

	public AuthorSubmitsFrame(User the_user, Conference the_conf) {
		my_mainGUI = new JFrame("Author: Submit Manuscript");
		my_title_panel = new JPanel();
		my_submit_panel = new JPanel();
		my_upload_panel = new JPanel();
		my_text_field = new JTextField("No File Selected");
		my_current_selected = new JLabel("No Selected File");
		my_user = the_user;
		my_conference = the_conf;
	    my_file_chooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
	}//end of Constructor
	
	public void start() {
		
		Border blackborder = BorderFactory.createLineBorder(Color.BLACK);
		
		my_submit_panel.setBorder(blackborder);// unsubmit?
		my_title_panel.setBorder(blackborder);// Where the titles are
		my_upload_panel.setBorder(blackborder);// bottom upload area
		
		// StartTask: Layout
		GridBagLayout gbl = new GridBagLayout();
		my_mainGUI.setLayout(gbl);
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;
		
		// Set up Title Panel
		gbc.weightx = 6;
		gbc.weighty = 4.5;
		gbl.setConstraints(my_title_panel, gbc);
		my_mainGUI.add(my_title_panel, gbc);
		
		// Set up Submit Panel
		gbc.weightx = 3;
		gbc.gridwidth = GridBagConstraints.REMAINDER;
		gbl.setConstraints(my_submit_panel, gbc);
		my_mainGUI.add(my_submit_panel, gbc);
		
		// Set up Upload Panel
		gbc.weighty = 1;
		gbl.setConstraints(my_upload_panel, gbc);
		my_mainGUI.add(my_upload_panel, gbc);
		
		// EndTask: Layout
		
		// Task: Panels - setting labels, buttons, etc for each panel
		
		// my_title_panel and buttonPanel
		JLabel titlePanelLabel = new JLabel("My Submitted Manuscripts");
		my_title_panel.setLayout(new BorderLayout());
		my_title_panel.add(titlePanelLabel, BorderLayout.NORTH);
		
		final JPanel buttonPanel = new JPanel();
		GridBagLayout buttonPanelGrid = new GridBagLayout();
		final GridBagConstraints bpc = new GridBagConstraints();
		buttonPanel.setLayout(buttonPanelGrid);
		bpc.fill = GridBagConstraints.BOTH;
		bpc.gridy = 0;
	
		repopulateMansuscripts(buttonPanel, bpc);
			
		JScrollPane scroll1 = new JScrollPane(buttonPanel);
		scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		my_title_panel.add(scroll1, BorderLayout.CENTER);
		
		// my_submit_panel
		JLabel submitPanelLabel = new JLabel("Selected File:");
		JButton unsubmitButton = new JButton("UNSUBMIT");
		unsubmitButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//TODO throw warning for user
				Iterator<Manuscript> iterator = my_conference.getManuscripts().iterator();
				while(iterator.hasNext()) {
					final Manuscript m = iterator.next();
					if(m.getTitle() == my_current_selected.getText()) {
						my_conference.deleteManuscript(m);
						my_current_selected.setText("No File Selected");
					}
				}
				repopulateMansuscripts(buttonPanel, bpc);
				buttonPanel.revalidate();
				buttonPanel.repaint(); 
			}
		});
		
		my_submit_panel.setLayout(new BorderLayout());
		my_submit_panel.add(submitPanelLabel, BorderLayout.NORTH);
		my_submit_panel.add(unsubmitButton, BorderLayout.SOUTH);
		my_submit_panel.add(my_current_selected, BorderLayout.CENTER);

		// my_upload_panel
		GridBagConstraints gbc2 = new GridBagConstraints();
		GridBagLayout gbl2 = new GridBagLayout();
		my_upload_panel.setLayout(gbl2);
		gbc2.fill = GridBagConstraints.BOTH;
		
		// upload new manuscript label
		gbc2.gridwidth = GridBagConstraints.REMAINDER;
		JLabel uploadPanelLabel = new JLabel("UPLOAD NEW MANUSCRIPT");
		gbl2.setConstraints(uploadPanelLabel, gbc2);
		my_upload_panel.add( uploadPanelLabel, gbc2);
		
		// blank panel
		gbc2.gridwidth = 1;
		gbc2.weightx = 1.5;
		JPanel emptyPanel = new JPanel();
		gbl2.setConstraints(emptyPanel, gbc2);
		my_upload_panel.add(emptyPanel, gbc2);
		
		// "Type Title" label
		gbc2.weightx = 7.5;
		gbc2.gridwidth = GridBagConstraints.REMAINDER;
		JLabel titleForTextBox = new JLabel("Type Title");
		gbl2.setConstraints(titleForTextBox, gbc2);
		my_upload_panel.add( titleForTextBox, gbc2 );
		
		// blank panel
		gbc2.gridwidth = 1;
		gbc2.weightx = 1;
		JButton chooseButton = new JButton("CHOOSE...");
		chooseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				File file = doChoose();
				my_text_field.setText(file.getPath());
			}
		});
		gbl2.setConstraints(chooseButton, gbc2);
		my_upload_panel.add(chooseButton, gbc2);
		
		// textfield
		gbc2.weightx = 2.5;
		//JTextField textField = new JTextField();
		gbl2.setConstraints(my_text_field, gbc2);
		my_upload_panel.add(my_text_field, gbc2);
		
		// blank panel
		gbc2.weightx = 1;
		JPanel emptyPanel3 = new JPanel();
		gbl2.setConstraints(emptyPanel3, gbc2);
		my_upload_panel.add(emptyPanel3, gbc2);
		
		// upload button
		gbc2.weightx = 1;
		JButton uploadButton = new JButton("UPLOAD");
		uploadButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//Check Format
				String text = my_text_field.getText();
				if(!text.substring(text.length() - 4).equals(".txt")) {
					JOptionPane.showMessageDialog(null, "File not .txt format!");
					return;
				}
				final GregorianCalendar today = new GregorianCalendar();
				//Test for deadline
				if(my_conference.getManuscriptDeadline().after(today)) { 
					addUploadedButton(buttonPanel, bpc);
				} else {
					JOptionPane.showMessageDialog(null, "The manuscript submission deadline has passed");
				}
				//Adding the manuscript to my_conf is handled in the helper method.
				//Now throws a warning and stops inside addUploadedButton
			}
		});
		
		gbl2.setConstraints(uploadButton, gbc2);
		my_upload_panel.add( uploadButton, gbc2 );
		
		// blank panel
		gbc2.gridwidth = GridBagConstraints.REMAINDER;
		gbc2.weightx = 4.5;
		JPanel emptyPanel4 = new JPanel();
		gbl2.setConstraints(emptyPanel4, gbc2);
		my_upload_panel.add(emptyPanel4, gbc2);
		
		// blank panel
		gbc2.gridwidth = 1;
		gbc2.weightx = 4.5;
		JPanel emptyPanel5 = new JPanel();
		gbl2.setConstraints(emptyPanel5, gbc2);
		my_upload_panel.add(emptyPanel5, gbc2);
		
		// cancel button
		gbc2.weightx = 1;
		JButton cancelButton = new JButton("CANCEL");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				my_text_field.setText("No File Selected");
			}
		});
		gbl2.setConstraints(cancelButton, gbc2);
		my_upload_panel.add(cancelButton, gbc2);
		
		// blank panel
		gbc2.weightx = 0.5;
		JPanel emptyPanel6 = new JPanel();
		gbl2.setConstraints(emptyPanel6, gbc2);
		my_upload_panel.add(emptyPanel6, gbc2);
		
		// close button
		gbc2.weightx = 1;
		JButton closeButton = new JButton("CLOSE");
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				my_conference.save();
				StartFrame back = new StartFrame();
				back.start();
				my_mainGUI.dispose();
			}
		});
		gbl2.setConstraints(closeButton, gbc2);
		my_upload_panel.add(closeButton, gbc2);
		
		// blank panel
		gbc2.weightx = 3;
		gbc2.gridwidth = GridBagConstraints.REMAINDER;
		JPanel emptyPanel7 = new JPanel();
		gbl2.setConstraints(emptyPanel7, gbc2);
		my_upload_panel.add(emptyPanel7, gbc2);
		
		// blank panel
		gbc2.weightx = 0.5;
		JPanel emptyPanel8 = new JPanel();
		gbl2.setConstraints(emptyPanel8, gbc2);
		my_upload_panel.add(emptyPanel8, gbc2);	
		
		//Some Settings
		my_mainGUI.setSize(700, 350);
		my_mainGUI.setVisible(true);
		my_mainGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}//end of Start
	
	
	/**
	 * This helper method adds a new button
	 *  onto the uploaded Manuscript panel.
	 * @param the_parent The parent panel, which should always be buttonPanel
	 * @param the_constraints The constraints being used by that panel. 
	 */
	private void addUploadedButton(JPanel the_parent, GridBagConstraints the_constraints) {
		my_selected_file = new File(my_text_field.getText());
		String titlename = my_selected_file.getName();
		titlename = titlename.substring(0, titlename.length()-4);
		try {
			my_conference.addManuscript(new Manuscript(titlename, 
					my_user.getName(), my_user.getID(), getFileBody()));
			final JButton button = new JButton();
			button.setText(titlename);
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					my_current_selected.setText(button.getText());
				}
			});
			final GridBagLayout layout = (GridBagLayout) the_parent.getLayout();
			layout.setConstraints(button, the_constraints);
			the_parent.add(button);
			the_constraints.gridy = the_constraints.gridy + 1;
			the_parent.revalidate();
			the_parent.repaint();
		} catch (FileNotFoundException e1) {
			JOptionPane.showMessageDialog(null, "Invalid File!");
		}
	}
	
	//TODO format here is odd?
	private void repopulateMansuscripts(JPanel the_parent, 
			GridBagConstraints the_constraints) {
		
		the_parent.removeAll();
		Iterator<Manuscript> iterator = my_conference.getManuscripts().iterator();
		while(iterator.hasNext()) {
			final Manuscript m = iterator.next();
			if(m.getAuthorID() == my_user.getID()) {
				final JButton button = new JButton();
				button.setText(m.getTitle());
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						my_current_selected.setText(button.getText());
					}
				});
				
				GridBagLayout layout = (GridBagLayout) the_parent.getLayout();
				layout.setConstraints(button, the_constraints);
				the_parent.add(button);
				the_constraints.gridy = the_constraints.gridy + 1;
				the_parent.revalidate();
				the_parent.repaint();
			}
		}
	}
	
	/**
	 * A FileChooser dialog appears asking for a text file.
	 * @return The selected File Object
	 */
	private File doChoose() {
		final int result = my_file_chooser.showOpenDialog(null);
		File textFile = new File("No File Selected");
		if (result == JFileChooser.APPROVE_OPTION){
			textFile = my_file_chooser.getSelectedFile();
			JOptionPane.showMessageDialog(null, "File Selected!");
		}
		else if (result == JFileChooser.CANCEL_OPTION) {
			JOptionPane.showMessageDialog(null, "Action Cancelled");
	    }
		return textFile;
	}//end of ChooseFile

	/**
	 * Collects the data in a file as one long string.
	 * 
	 * @author Cristopher
	 * @return the string representation of the file
	 * @throws FileNotFoundException if my_selected_file is not found
	 */
	private String getFileBody() throws FileNotFoundException {
		Scanner read = new Scanner(new FileReader(my_selected_file));
		StringBuilder body = new StringBuilder();
		try {
			while (read.hasNextLine()) {
				body.append(read.nextLine());
			}
		} finally {
			read.close();
		}
		return body.toString();
	}// end of getBody
}//end of AuthorSubmitsFrame
